<?
/*
*
*  ImageResizer
*   Class for image resizing
*/

class ImageResizer {
   
   function ImageResizer() {
   		return $this;
   }
   
   public function Resize($imgSrc, $limit_dst){
    global $IMG_DIR, $IMG_URL;
      //header("Content-type: image/jpeg");
      $im = @imagecreatefromjpeg ($imgSrc);
	  list($width, $height, $type, $attr) = getimagesize($imgSrc);
         if($width > $height) // if 510 > 361
		 {
            $width_dst = $limit_dst; // h = 150
			$prop = $width/$height; // prop = 510/361 =1.412
			$height_dst = $width_dst / $prop;	// height = 150 / 1.412		
         } elseif( $height > $width) { // 361 < 510
		    $height_dst = $limit_dst;  // h = 150
			$prop = $width / $height; // prop = 510 / 361 = 0.7
			$width_dst = $height_dst * $prop; // width = 150 * 1.412
		} elseif ($height == $width){
			$height_dst = $limit_dst;  // h = 150
			$prop = $width / $height; // prop = 510 / 361 = 0.7
			$width_dst = $height_dst * $prop;
		}
		$im_d = @imagecreatetruecolor($width_dst, $height_dst) or die ("Cannot Initialize new GD image stream");
		$this->ImageCopyResampleBicubic($im_d, $im, 0, 0, 0, 0, $width_dst, $height_dst, $width, $height);
		
		mt_srand($this->make_seed());
        $randval = mt_rand();
		$file = $randval.'.jpg';
		$img_thumb_file = $IMG_DIR."/thumbs/".$file;
		
		$img_thumb_url = $IMG_URL."/thumbs/".$file;
		imagejpeg($im_d , $img_thumb_file , 70);
		chmod ($img_thumb_file, 0660);
 	  	imagedestroy($im_d);
   	  	imagedestroy($im);
		return	$img_thumb_url;
   }
   
   private function ImageCopyResampleBicubic (&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
      ImagePaletteCopy ($dst_img, $src_img);
         $rX = $src_w / $dst_w;
         $rY = $src_h / $dst_h;
         $w = 0;
         for ($y = $dst_y; $y < $dst_h; $y++) {
            $ow = $w; $w = round(($y + 1) * $rY);
            $t = 0;
               for ($x = $dst_x; $x < $dst_w; $x++) {
                  $r = $g = $b = 0; $a = 0;
                  $ot = $t; $t = round(($x + 1) * $rX);
                     for ($u = 0; $u < ($w - $ow); $u++) {
                        for ($p = 0; $p < ($t - $ot); $p++) {
                           $c = ImageColorsForIndex ($src_img, ImageColorAt ($src_img, $ot + $p, $ow + $u));
                           $r += $c['red'];
                           $g += $c['green'];
                           $b += $c['blue'];
                           $a++;
                        }
                     }
                  ImageSetPixel ($dst_img, $x, $y, ImageColorClosest ($dst_img, $r / $a, $g / $a, $b / $a)); 
               }
         }
   } // end function
   
   private function make_seed()
   {
      list($usec, $sec) = explode(' ', microtime());
      return (float) $sec + ((float) $usec * 100000);
   }
    

   
}
?>